//
//  SettingViewCtrl.m
//  AccuroFit
//
//  Created by NCIT Developer on 3/10/16.
//  Copyright © 2016 Nci Technology Inc. All rights reserved.
//

/*#import <AudioToolbox/AudioServices.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#import "Reachability.h"

#import "AppDelegate.h"

#import "SettingViewCtrl.h"

#define _ScaleHostPort 3000
#define _ScaleHostIpAddr "192.168.1.1"


@interface SettingViewCtrl ()

@end

@implementation SettingViewCtrl {
  UILabel* _lblMsg;
  UISegmentedControl* _scSettingType;
  UILabel* _lblBfs200Setting;
  
  UILabel* _lblRouterName;
  UIButton* _btnRefreshRouter;
  UITextField* _txtPswdRouter;
  
  UIButton* _btnNext;
  UIButton* _btnSetting;
  UIButton* _btnCancel;
  
  UIImageView* _ivRouter;
  
  
  BOOL _bHostWiFiConn;
  in_addr_t _nIpAddr;
  uint16_t _port;
  
  //NcitWiFiDev *_socketSvr;
  Reachability* _wifiScaleHost;
  
  NSMutableArray *t_devicelist;   //device name
}

//define tag number
#define tag_table_main      1
#define tag_table_confirm   2

#define tag_timer           10101

#define tag_ctl_TEXTpincode 10201
#define tag_ctl_VIEWshow    10301
#define tag_ctl_VIEWaction  10302

#define tag_cfg_TEXTpincode 10501
#define tag_cfg_VIEWshow    10601
#define tag_cfg_VIEWwifi    10602
#define tag_cfg_confirm     10603
#define tag_ctl_rename      10604
#define tag_ctl_renameEND   10605
#define tag_ctl_remove      10606
#define tag_ctl_removeEND   10607

//define timout
#define timeout_cfg         120
#define timeout_discovery   4.0
#define timeout_control     20.0


typedef enum {
  NONE_STATE, SCAN_STATE, CONFIGURE_STATE, CONTROL_STATE
} EventType;

@synthesize mySimpleConfig;
@synthesize myAESKey;
@synthesize myTimer;
@synthesize myDevType;

//@synthesize m_pin_code;

@synthesize waitingAlert;

UITextField *text_pincode;

Boolean isShowDiscoveryDevice = false;
Boolean isShowCtlRename       = false;
Boolean isShowCtlRemove       = false;
Boolean isQRcodeAction        = false;
Boolean isCfgPIN              = false;
Boolean isCtlPIN              = false;

NSMutableArray *discovery_deviceList;   //context:  dev_info(struct)
NSMutableArray *config_deviceList;      //context:  dev_info(struct)

NSString *newDeviceName = nil;
NSString *SSID = nil;
NSString *AP_password = nil;
NSString *PIN_cfg = nil, *PIN_ctl = nil;
NSString *PIN_backdoor = @"00000000";

NSString *dev_Iphone = @"iPhone";
NSString *dev_Ipad   = @"iPad";

NSTimer *waitTimer,*discoveryTimer;
NSTimer *cfgTimer;
NSData *bcastdata;

UIAlertView *ctlPINAlert;
UIAlertView *cfgPINAlert;

UILabel *lblDownloadPercent;

UIProgressView *cfgProgressView;

NSUserDefaults *APInfo_DataFile = nil;      //SSID1,password1;SSID,password2;...
NSUserDefaults *PINCode_DataFile = nil;     //mac1,PIN1;mac2,PIN2;...

//int checkFinishWait_cfg = 20;
int checkFinishWait_control = 20;

unsigned int bcastip = 0;
unsigned int timerCount = 0;
static int curr_control_type = 0;
EventType curr_event;
dev_info  curDevInfo;

// Timer Handler
- (void)handleTimer: (NSTimer *)sender
{
  int ret = -1;
  int indexItem = 0;
  switch (curr_event) {
    case NONE_STATE:
      break;
    case SCAN_STATE:
      curr_event = NONE_STATE;
      break;
    case CONFIGURE_STATE:
      
      if (timerCount++ < timeout_cfg)
      {
        NSLog(@"<APP> wait %d for config ack!!!!!!!!!!!!\n",timerCount);
        
        if ([self.mySimpleConfig rtk_sc_get_cfgACK_state] && timerCount%3==0) { //check cfg ACK state
          if (timerCount>30)
          {
            //NSLog(@"<APP> Config phase two");
            [self.mySimpleConfig rtk_sc_set_profileSendInterval:500000]; //500ms
            [self.mySimpleConfig rtk_sc_set_packetSendInterval:5000];    //5ms
            [self.mySimpleConfig rtk_sc_set_eachPacketCounts:1];
          }
        }
        
        
        // 4. update result, and check configure timeout
        //if ([self.mySimpleConfig.pattern.ack_host count]==0)
        if ([self.mySimpleConfig rtk_get_connected_sta_num]==0) {
          return ;
        }
        
        //after ack and then wait 5s for all device config finish
        //if( (checkFinishWait_cfg--) >0)
        //    return;
        
        //checkFinishWait_cfg = 20;
        
        timerCount = 0;
        [self stopWaiting];
        
        int ackHostNum = [self.mySimpleConfig rtk_get_connected_sta_num];
        //int connectedNum = 0;
        
        //if ([self.mySimpleConfig.pattern.ack_host count]>0 || [self.mySimpleConfig rtk_get_connected_sta_num]>0){
        if (ackHostNum>0){
          
          //connectedNum = [self.mySimpleConfig rtk_get_connected_sta_num];
          
          NSValue *dev = nil;//[self.mySimpleConfig.pattern.extend_ack_host objectAtIndex:0];
          dev_info curr_dev;
          
          //config_deviceList = [NSMutableArray arrayWithObjects:nil];
          //t_devicelist = [NSMutableArray arrayWithObjects:nil];
          config_deviceList = [NSMutableArray arrayWithCapacity:0];
          t_devicelist = [NSMutableArray arrayWithCapacity:0];
          
          for (indexItem=0; indexItem< ackHostNum; indexItem++) {
            //mac = [[NSString alloc]initWithString:[self.mySimpleConfig.pattern.ack_host objectAtIndex:indexItem]];
            //[t_devicelist addObject:mac];
            
            dev = [self.mySimpleConfig.pattern.extend_ack_host objectAtIndex:indexItem];
            [dev getValue:&curr_dev];
            
            if(curr_dev.dev_name==nil)curr_dev.dev_name=curr_dev.macAddress;
            
            NSLog(@"<APP> curr_dev name is %@\nip is %x\nmac is %@\ntype is %s\n"
                  , curr_dev.dev_name
                  , curr_dev.ip
                  , curr_dev.macAddress
                  , curr_dev.type);
            [t_devicelist addObject:curr_dev.dev_name];
            
            curr_dev.type[0] = 1;
            curr_dev.type[1] = 1;
            
            NSValue *deviceItem = [NSValue value:&curr_dev withObjCType:@encode(dev_info)];
            [config_deviceList addObject:deviceItem];
            
          }
          
          discovery_deviceList = nil;
          [discovery_deviceList addObject:config_deviceList];
          
          [self.mySimpleConfig rtk_sc_stop];
          [self.tableDeviceList reloadData];
          
          [self showConfirmConfigDevice];
          curr_event = NONE_STATE;
          
        }
      }
      else {
        [self.mySimpleConfig rtk_sc_stop];
        
        //if ([self.mySimpleConfig.pattern.ack_host count]==0)
        {
          UIAlertView* confirm_alert = [[UIAlertView alloc] initWithTitle:@"Configure Timeout"
                                                                  message:@""
                                                                 delegate:self
                                                        cancelButtonTitle:NSLocalizedString(@"OK", nil)
                                                        otherButtonTitles: nil];
          
          [confirm_alert show];
        }
        curr_event = NONE_STATE;
        [self stopWaiting];
        timerCount = 0;
        
      }
      
      break;
    case CONTROL_STATE:
      
      if (timerCount++ < timeout_control)
      {
        ret = [self.mySimpleConfig rtk_sc_get_control_result];
        if (ret!=1) { //status:1 success
          NSLog(@"<APP> wait control ack");
          if (curr_control_type == SC_RENAME_DEV) {
            NSData *rename_data = [self.mySimpleConfig rtk_sc_gen_rename_dev_packet:newDeviceName];
            [self.mySimpleConfig rtk_sc_send_rename_dev_packet:rename_data ip:curDevInfo.ip];
          }else if(curr_control_type == SC_DELETE_PROFILE){
            NSData *remove_data = [self.mySimpleConfig rtk_sc_gen_control_packet:curr_control_type];
            [self.mySimpleConfig rtk_sc_send_control_packet:remove_data ip:curDevInfo.ip];
          }
          
          return;
        }
        
        if(timerCount!=timeout_control)
        {
          if (curr_control_type == SC_RENAME_DEV) {
            checkFinishWait_control-=2;
            NSLog(@"wait rename finish: %d",checkFinishWait_control);
          }else if (curr_control_type == SC_DELETE_PROFILE){
            NSLog(@"wait remove finish: %d",checkFinishWait_control--);
          }
          
          //after ack and then wait 8s for all device config finish
          if( checkFinishWait_control >0)
            return;
        }
        checkFinishWait_control = 20;
        
        if (curr_control_type == SC_RENAME_DEV) {
          isShowCtlRename = false;
          [self showRenameResult];
          
        }else if (curr_control_type == SC_DELETE_PROFILE){
          isShowCtlRemove = false;
          [self showRemoveResult];
          
        }else
          return;
        
        [self stopTimerAction];
        curr_event = NONE_STATE;
        timerCount = 0;
        
      }else{
        NSString *alerttitle = nil;
        [self stopTimerAction];
        curr_event = NONE_STATE;
        timerCount = 0;
        
        if (curr_control_type == SC_RENAME_DEV) {
          alerttitle = @"Rename Timeout";
        }else if (curr_control_type == SC_DELETE_PROFILE){
          alerttitle = @"Remove Timeout";
        }
        
        UIAlertView* ret_alert = [[UIAlertView alloc] initWithTitle:alerttitle
                                                            message:@""
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"OK", nil)
                                                  otherButtonTitles: nil];
        
        [ret_alert show];
      }
      
      break;
      
    default:
      break;
      
  }
}

- (void) startCongigRouter
{
  NSLog(@"<APP> configure condition:key in pin code - skip");
  [self.mySimpleConfig.pattern set_index:2];
  
  //[self startWaiting:@"Device Configuring":-1]; skip
  [self startWaiting_progress:@"Device Configuring":120];
  
  NSLog(@"<APP> Configure start");
  
  // Step 1: check necessary items: SSID, PSW and key if necessary, and lock these input textfield
  int chk_result = [self check_cfgData];
  if(chk_result>=0) {
    // Step 2: clear the buffer and set items to mib
    //NSString *user_pin = myAESKey.text;
    //[self.mySimpleConfig rtk_sc_set_pin:pinskip];
    //self.mySimpleConfig.pattern.have_pin = 1;
    [self.mySimpleConfig rtk_sc_set_ssid: SSID];
    [self.mySimpleConfig rtk_sc_set_password: AP_password];
    
    NSLog(@"<APP> SSID: %@", self.mySimpleConfig.pattern.m_ssid);
    NSLog(@"<APP> PSW: %@", self.mySimpleConfig.pattern.m_psw);
    NSLog(@"<APP> PIN: %@", self.mySimpleConfig.pattern.m_pin);
    
    // Step 3: do simple config
    [self.mySimpleConfig rtk_sc_gen_random];
    [self.mySimpleConfig rtk_sc_build_profile];
    //[self.mySimpleConfig rtk_sc_set_profileSendInterval:150000]; //150ms
    //[self.mySimpleConfig rtk_sc_set_packetSendInterval:2];      //2ms
    //[self.mySimpleConfig rtk_sc_set_eachPacketCounts:1];
    [self setTimePacketPrarmeter];
    
    curr_event = CONFIGURE_STATE;
    isCfgPIN = false;
    //[self startTheBackground_cfg];
    //cfgTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(handleCfgTimer:) userInfo:nil repeats:YES];
    
    [NSThread detachNewThreadSelector:@selector(handleConfigThread:) toTarget:self withObject:nil];
    
    NSLog(@"<APP> send config packet");
  }
  else {
    NSLog(@"<APP> Config error:%d",chk_result);
    curr_event = NONE_STATE;
    isCfgPIN = false;
  }
}

// configure Send Timer
- (void)handleConfigThread: (NSTimer *)sender
{
  [self.mySimpleConfig rtk_sc_start];
}

- (void) startWaiting_progress:(NSString *) wait_title :(float)timeout {
    if(waitTimer) {
      [self stopWaiting_progress];
    }
    
    //  Purchasing Spinner.
    waitingAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(wait_title,@"")
                    message:@"  Please wait...\n" delegate:self
                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                    otherButtonTitles:nil];
    waitingAlert.tag = tag_timer;
    
    waitingAlert.alertViewStyle = UIAlertViewStyleDefault;
    
    cfgProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    [cfgProgressView setTrackTintColor:[UIColor lightGrayColor]];
    [cfgProgressView setProgressTintColor:[UIColor blueColor]];
    cfgProgressView.frame = CGRectMake(20, 20, 200, 15);
    cfgProgressView.progress = 0;
    [waitingAlert setValue:cfgProgressView forKey:@"accessoryView"];
    
    CGRect lblDownloadPercentFrame = CGRectMake(self.tableDeviceList.frame.size.width-50
                                                , self.tableDeviceList.frame.size.height-35, 60, 20);
    //lblDownloadPercent = [waitingAlert textFieldAtIndex:0];
    lblDownloadPercent = [[UILabel alloc]initWithFrame:lblDownloadPercentFrame];
    lblDownloadPercent.textColor = [UIColor whiteColor];
    lblDownloadPercent.backgroundColor = [UIColor clearColor];
    //[waitingAlert setValue:lblDownloadPercent forKey:@"accessoryView"];
    
    [waitingAlert show];
    
    if (timeout>0) {
      waitTimer = [NSTimer scheduledTimerWithTimeInterval:1.2 target:self selector:@selector(update) userInfo:nil repeats:true];
    }
}
  
- (void)stopWaiting_progress{
  [self.mySimpleConfig rtk_sc_stop];
  if(waitTimer){
    [waitTimer invalidate];
    waitTimer = nil;
  }
  
  if (waitingAlert) {
    [waitingAlert dismissWithClickedButtonIndex:0 animated:YES];
    waitingAlert = nil;
  }
  curr_event = NONE_STATE;
}

- (void)setTimePacketPrarmeter
{
  [self.mySimpleConfig rtk_sc_set_profileSendInterval:200000]; //200ms
  [self.mySimpleConfig rtk_sc_set_packetSendInterval:10];      //10ms
  [self.mySimpleConfig rtk_sc_set_eachPacketCounts:1];
}

- (void)stopWaiting
{
  
  [self stopTimerAction];
}

-(void)showRemoveResult
{
  int control_result = [self.mySimpleConfig rtk_sc_get_control_result];
  if (control_result==1) {
    
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"Delete device successfully", @"AlertView")
                              message:NSLocalizedString(@"", @"AlertView")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                              otherButtonTitles:nil];
    alertView.tag = tag_ctl_removeEND;
    [alertView show];
  }else if(control_result==0){
    
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"Delete device failed", @"AlertView")
                              message:NSLocalizedString(@"", @"AlertView")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                              otherButtonTitles:nil];
    [alertView show];
  }
}

-(void)stopTimerAction
{
  [self.mySimpleConfig rtk_sc_stop];
  if(waitTimer){
    [waitTimer invalidate];
    waitTimer = nil;
  }
  if (discoveryTimer){
    [discoveryTimer invalidate];
    discoveryTimer = nil;
  }
  
  if (waitingAlert) {
    [waitingAlert dismissWithClickedButtonIndex:0 animated:YES];
    waitingAlert = nil;
  }
  curr_event = NONE_STATE;
}

-(void) showConfirmConfigDevice
{
  [self stopWaiting];
  
  if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
    // do stuff for iOS 7 and newer
    UIAlertView* confirm_alert = [[UIAlertView alloc] initWithTitle:@"Configured Device"
                                  //message:@"\n\n\n\n\n\n\n\n\n\n"
                                                            message:@"uncheck device if any unwanted!"
                                                           delegate:self
                                                  cancelButtonTitle:@"Confirm"
                                                  otherButtonTitles: nil];
    
    confirm_alert.tag = tag_cfg_confirm;
    int table_width = 264;
    int table_height = 210;
    if ([config_deviceList count]>0) {
      table_height = 75 * (int)[t_devicelist count];
      
      if(table_height>400)
        table_height = 400;
      if (table_height<90) {
        table_height = 90;
      }
    }
    
    UITableView* myView = [[UITableView alloc] initWithFrame:CGRectMake(10, 45, table_width, table_height)
                                                       style:UITableViewStyleGrouped];
    myView.tag = tag_table_confirm;
    [myView setAllowsSelection:NO];
    myView.delegate = self;
    myView.dataSource = self;
    myView.backgroundColor = [UIColor clearColor];
    [confirm_alert setValue:myView forKey:@"accessoryView"];
    [confirm_alert show];
  }else {
    // do stuff for older versions than iOS 7
    UIAlertView* confirm_alert = [[UIAlertView alloc] initWithTitle:@"Configured Device"
                                  //message:@"\n\n\n\n\n\n\n"
                                                            message:@"\n\n\n\n\n\n\n\n\n\n"
                                                           delegate:self
                                                  cancelButtonTitle:@"Confirm"
                                                  otherButtonTitles: nil];
    
    confirm_alert.tag = tag_cfg_confirm;
    
    UITableView* myView = [[UITableView alloc] initWithFrame:CGRectMake(10, 45, 264, 210)
                                                       style:UITableViewStyleGrouped];
    myView.tag = tag_table_confirm;
    [myView setAllowsSelection:NO];
    myView.delegate = self;
    myView.dataSource = self;
    myView.backgroundColor = [UIColor clearColor];
    [confirm_alert addSubview:myView];
    [confirm_alert show];
  }
}

-(void)showRenameResult
{
  int control_result = [self.mySimpleConfig rtk_sc_get_control_result];
  if (control_result==1) {
    
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"Rename device successfully", @"AlertView")
                              message:NSLocalizedString(@"", @"AlertView")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                              otherButtonTitles:nil];
    alertView.tag = tag_ctl_renameEND;
    [alertView show];
  }else if(control_result==0){
    
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"Rename device failed", @"AlertView")
                              message:NSLocalizedString(@"", @"AlertView")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                              otherButtonTitles:nil];
    [alertView show];
  }
}

- (void) update{
  
  cfgProgressView.progress +=0.01;
  
  //when 100%
  if (cfgProgressView.progress == 1)
  {
    [self stopWaiting_progress];
    
    cfgProgressView.progress = 0;
  }
}

  //--------------------------------- sub utility ---------------------------------
  -(int) check_cfgData
  {
    
    if ( PIN_cfg==nil ) {
      return 0;
    }else if (SSID==nil){
      return -1;
    }else if (AP_password==nil){
      return -2;
    }
    
    return 1;
  }


// 是否wifi
- (BOOL) IsEnableWIFI {
  return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

- (void)Discovery_triger
{
  [self Discovery_btnClik:nil];
}


- (IBAction)Discovery_btnClik:(id)sender
{
  if([self IsEnableWIFI])
  {
    
    [self.mySimpleConfig rtk_sc_stop];
    [self.mySimpleConfig rtk_sc_exit];
    
    //t_devicelist = [NSMutableArray arrayWithObjects:nil];
    t_devicelist = [NSMutableArray arrayWithCapacity:0];
    [self.tableDeviceList reloadData];
    
    isShowDiscoveryDevice = true;
    
    NSLog(@"<APP> Start to scan device!");
    
    //step 1: clear previous dev list
    [self.mySimpleConfig.pattern.dev_connected_list removeAllObjects];
    [self.mySimpleConfig rtk_sc_clear_device_list];
    
    //step 2: gen and send scan data
    NSString *str_bcastip = [self getIP_bcast];
    NSArray *subip = [str_bcastip componentsSeparatedByString:@"."];
    bcastip = ([subip[0] intValue]<<24) + ([subip[1] intValue]<<16) + ([subip[2] intValue]<<8) + ([subip[3] intValue]);
    NSLog(@"<APP> bcast ip : %x",bcastip);
    
    //[self.mySimpleConfig rtk_sc_set_control_password:nil];
    bcastdata = [self.mySimpleConfig rtk_sc_gen_discover_packet];
    
    [self startWaiting:@"Searching Devices":timeout_discovery];
    
    [self.mySimpleConfig rtk_sc_send_discover_packet:bcastdata ip:bcastip];
    discoveryTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(sendDiscoveryCommand) userInfo:nil repeats:YES];
    
    [NSTimer scheduledTimerWithTimeInterval: timeout_discovery
     target:self selector:@selector(showDiscoveryDevice)
     userInfo: nil repeats:NO];
    
  }else{
    UIAlertView *wifialertView = [[UIAlertView alloc]
                                  initWithTitle:NSLocalizedString(@"No WIFI available!", @"AlertView")
                                  message:NSLocalizedString(@"You have no wifi connection available. Please connect to a WIFI network.", @"AlertView")
                                  delegate:self
                                  cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                                  otherButtonTitles:nil];
    [wifialertView show];
  }
}

-(NSString *)getIP_bcast
{
  NSString *address = @"error";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;
  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&interfaces);
  if (success == 0) {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL) {
      if(temp_addr->ifa_addr->sa_family == AF_INET) {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
          // Get NSString from C String
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
        }
      }
      temp_addr = temp_addr->ifa_next;
    }
  }
  freeifaddrs(interfaces);
  return address;
}

//show loading activity.
- (void)startWaiting:(NSString *) wait_title :(float)timeout {
  
  if(waitTimer){
    [self stopWaiting];
  }
  
  //  Purchasing Spinner.
  if (!waitingAlert) {
    waitingAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(wait_title,@"")
                    message:@"  Please wait...\n" delegate:self
                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:nil];
    waitingAlert.tag = tag_timer;
    
    if( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1){
      // do stuff for iOS 8 and newer
      //float version = floor(NSFoundationVersionNumber);
      
      //int www = waitingAlert.frame.size.width;
      //int hhh = waitingAlert.frame.size.height;
      
      UIActivityIndicatorView *actview = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
      actview.color=[UIColor blackColor];
      //actview.center=CGPointMake(www/2, hhh/2);
      [actview startAnimating];
      
      [waitingAlert setValue:actview forKey:@"accessoryView"];
      
      
      
    }else if ( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
      // do stuff for iOS 7 and newer
      UIView *v=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
      v.backgroundColor=[UIColor whiteColor];
      v.layer.masksToBounds = YES;
      v.layer.cornerRadius = 6.0;
      v.layer.borderWidth = 1;
      v.layer.borderColor = [[UIColor lightGrayColor] CGColor];
      [self.view addSubview:v];
      
      UIActivityIndicatorView *actview = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
      actview.color=[UIColor blackColor];
      actview.center=CGPointMake(v.frame.size.width/2, v.frame.size.height/2);
      [actview startAnimating];
      [v addSubview:actview];
      
      [waitingAlert setValue:v forKey:@"accessoryView"];
    }else {
      // do stuff for older versions than iOS 7
      [waitingAlert show];
      
      
      UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
      //connectingIndicator.frame = CGRectMake(139.0f-18.0f,50.0f,37.0f,37.0f);
      waitingIndicator.frame = CGRectMake(20.0f,40.0f,37.0f,37.0f);
      [waitingAlert addSubview:waitingIndicator];
      [waitingIndicator startAnimating];
    }
    
    
    [waitingAlert show];
    
    if (timeout>0) {
      waitTimer = [NSTimer scheduledTimerWithTimeInterval: timeout
                  target: self selector:@selector(stopWaiting)
                  userInfo: nil repeats:NO];
    }
    
    
  }
}

-(void)sendDiscoveryCommand
{
  [self.mySimpleConfig rtk_sc_send_discover_packet:bcastdata ip:bcastip];
}

-(void)showDiscoveryDevice
{
  //discovery_deviceList = [NSMutableArray arrayWithObjects:nil];
  discovery_deviceList = [NSMutableArray arrayWithCapacity:0];
  
  int size = (int)[self.mySimpleConfig.pattern.dev_connected_list count];
  
  //NSMutableArray *dev_list = [self.mySimpleConfig rtk_sc_get_discovered_devices];
  //size = (int)[dev_list count];
  
  if(size>0)
  {
    int i = 0;
    //int j = 0;
    //dev_info pDevInfo;
    BOOL isInsert = true;
    dev_info d;
    NSValue *dev    = [[NSValue  alloc]init];
    
    for (i=0; i<size; i++) {
      dev = [self.mySimpleConfig.pattern.dev_connected_list objectAtIndex:i];
      [dev getValue:&d];
      NSLog(@"<APP> ===[row %d]=== \nname:%@\nip:%x\nmac:%@\ntype:%s\n", i+1, d.dev_name,d.ip,d.macAddress,d.type);
      
      isInsert = true;
      
      if (isInsert)
      {
        NSValue *deviceItem = [NSValue value:&d withObjCType:@encode(dev_info)];
        [discovery_deviceList addObject:deviceItem];
        
        if ((d.dev_name==nil) || ([d.dev_name isEqualToString:@""])) {
          
          [t_devicelist addObject:d.macAddress];
          
        }else{
          [t_devicelist addObject:d.dev_name];
        }
      }
      
    }
    //t_devicelist = [[NSMutableArray alloc] initWithObjects:self.mySimpleConfig.pattern.dev_connected_list,nil];
    //[t_devicelist addObject:[NSString stringWithFormat:tmp]];
    //[t_devicelist addObject:[NSString stringWithFormat:d.dev_name]];
    
    
    [self.tableDeviceList reloadData];
  }
}

-(void)initData
{
  // Initialize table data
  //t_devicelist = [[NSMutableArray alloc] init];
  //t_devicelist = [NSMutableArray arrayWithObjects: nil];
  t_devicelist = [NSMutableArray arrayWithCapacity:0];
  
  [self.tableDeviceList reloadData];
  
  discovery_deviceList = [[NSMutableArray alloc] init];
  discovery_deviceList = nil;
  
  config_deviceList = [[NSMutableArray alloc] init];
  config_deviceList = nil;
  
  //init timer
  waitTimer = nil;
  
  // init the simpleConfig with Pattern 2
  NSString *pattern_name = @"sc_mcast_udp";
  self.mySimpleConfig = [[SimpleConfig alloc] initWithPattern:PATTERN_TWO flag:(PATTERN_USING_UDP_SOCKET | PATTERN_VALID ) name:pattern_name];
}

-(void) initComponent
{
  APInfo_DataFile = [NSUserDefaults standardUserDefaults];
  //PINCode_DataFile = [NSUserDefaults standardUserDefaults];
}

-(void)initComponentAction
{
  // init the timer, update timer every 1s
  self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
  
  if([discovery_deviceList count] == 0 && [self IsEnableWIFI]) {
    _btnNext.enabled = YES;
    [self Discovery_triger];
  }else{
    _btnNext.enabled = NO;
    UIAlertView *wifialertView = [[UIAlertView alloc]
                                  initWithTitle:NSLocalizedString(@"No WIFI available!", @"AlertView")
                                  message:NSLocalizedString(@"You have no wifi connection available. Please connect to a WIFI network.", @"AlertView")
                                  delegate:self
                                  cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"OK", nil), @"AlertView")
                                  otherButtonTitles:nil];
    [wifialertView show];
  }
}

//delegate
- (void)checkForWIFIConnection {
  Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
  NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
  if (netStatus!=ReachableViaWiFi)
  {
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:NSLocalizedString(@"No WIFI available!", @"AlertView")
                              message:NSLocalizedString(@"You have no wifi connection available. Please connect to a WIFI network.", @"AlertView")
                              delegate:self
                              cancelButtonTitle:NSLocalizedString(NSLocalizedString(@"Cancel", nil), @"AlertView")
                              otherButtonTitles:NSLocalizedString(@"Open settings", @"AlertView"), nil];
    [alertView show];
  }
}

//---------------------------------  UI table controllers  -------------------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *simpleTableIdentifier = @"Cell";
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
  
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
  }
  
  switch ([tableView tag]) {
    case tag_table_main:{
      cell.textLabel.text = [t_devicelist objectAtIndex:indexPath.row];
      cell.imageView.image = [UIImage imageNamed:@"ic_dialog_icon.png"];
      cell.imageView.frame = CGRectMake(cell.imageView.frame.origin.x, cell.imageView.frame.origin.y, 0, 0);
      cell.imageView.contentMode =UIViewContentModeScaleAspectFit;
      
      break;
    }
    case tag_table_confirm:{
      //cell.textLabel.text = [NSString stringWithFormat:@"Option %d", [indexPath row] + 1];
      cell.textLabel.text = [t_devicelist objectAtIndex:indexPath.row];
      cell.selectionStyle = UITableViewCellSelectionStyleNone;
      UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
      cell.accessoryView = switchView;
      switchView.tag= indexPath.row;
      [switchView setOn:YES animated:NO];
      [switchView addTarget:self action:@selector(cfgConfirmSwitched:) forControlEvents:UIControlEventValueChanged];
      break;
    }
    default:
      break;
  }
  
  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [t_devicelist count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  // Return the number of sections.
  return 1;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  // Return NO if you do not want the specified item to be editable.
  return YES;
}

-(void)cfgConfirmSwitched:(id) sender
{
  int rowIndex = (int)[sender tag];
  UISwitch* switchControl = sender;
  NSLog( @"switch(%d) is %@", rowIndex, switchControl.on ? @"ON" : @"OFF" );
  
  dev_info pDevInfo;
  int i = 0;
  
  //get the element(rowIndex) device
  [[config_deviceList objectAtIndex:rowIndex] getValue:&pDevInfo];
  if (switchControl.on) {
    pDevInfo.type[0] = 1;
    pDevInfo.type[1] = 1;
  }else{
    pDevInfo.type[0] = 0;
    pDevInfo.type[1] = 0;
  }
  
  //delete the element(rowIndex) device
  [config_deviceList removeObjectAtIndex:rowIndex];
  //insert the new element(rowIndex) device
  NSValue *deviceItem = [NSValue value:&pDevInfo withObjCType:@encode(dev_info)];
  [config_deviceList insertObject:deviceItem atIndex: rowIndex];
  
  for (i=0; i<[config_deviceList count]; i++) {
    [[config_deviceList objectAtIndex:i] getValue:&pDevInfo];
    NSLog(@"<APP> [after changed] name : %@\n",pDevInfo.dev_name);
    NSLog(@"<APP> [after changed] ip   : %x\n",pDevInfo.ip);
    NSLog(@"<APP> [after changed] mac  : %@\n",pDevInfo.macAddress);
    NSLog(@"<APP> [after changed] type : %d\n",pDevInfo.type[0]);
  }
  
  
}
//relteck end

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  self.view.backgroundColor = [UIColor colorWithWhite:0.125 alpha:0.5];
  
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  
  CGFloat yPos = (H <= 480)? 60: 65;
  [self initViewCtrls: yPos scrWdt: W scrHgt:H];
  
  //_bShowHbdp = YES;
  //_ptViewHbdp = _gViewHbdp.center;
  //_ptViewLbdp = _gViewLbdp.center;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.6];
  UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
  //self.navigationItem.leftBarButtonItem = leftButton;
  self.navigationItem.rightBarButtonItem = profButton;
  
  _bHostWiFiConn = NO;
  [self setConnectedRouter];
  
  [self initData];
  [self initComponent];
  [self initComponentAction];
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  BOOL bIpad = H > 1000;
  BOOL bWider = W > 320;
  BOOL bIp4s = H <= 480;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  BOOL bMgr = [pApp isUserMgr];
  //_socketSvr = pApp.m_ncitWiFiDev;
  
  CGFloat xPos = bWider?60:40;
  CGFloat yyPos = yPos-(bIp4s?15:0);
  _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos, W - xPos*2, 60)];
  _lblMsg.textColor = [UIColor whiteColor];
  _lblMsg.font = [UIFont systemFontOfSize:16.0];
  _lblMsg.backgroundColor = [UIColor clearColor];
  _lblMsg.textAlignment = NSTextAlignmentCenter; //bIpad? NSTextAlignmentCenter: NSTextAlignmentRight;
  
  _lblMsg.lineBreakMode = NSLineBreakByWordWrapping;
  _lblMsg.numberOfLines = 0;
  
  _lblMsg.text = @"WiFi Router Setting\n Please connect to Router first\n then input your router password";
  [self.view addSubview:_lblMsg];
  
  
  yyPos += (bIpad? 90: 80);
  if(bMgr) {
    xPos = (W - 200) / 2;
    _scSettingType = [[UISegmentedControl alloc] initWithFrame:CGRectMake(xPos, yyPos, 200, bIp4s?24:32)];
    _scSettingType.tintColor = [UIColor clearColor];
  
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor orangeColor]};
    [_scSettingType setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor lightTextColor]};
    [_scSettingType setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
 
    [_scSettingType insertSegmentWithTitle:@"BFS221" atIndex:0 animated:NO];
    [_scSettingType insertSegmentWithTitle:@"BFS200" atIndex:1 animated:NO];
    
    //_scSettingType.segmentedControlStyle = UISegmentedControlStyleBordered;
    _scSettingType.selectedSegmentIndex = bMgr?0: 1;
    _scSettingType.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _scSettingType.layer.cornerRadius = 4;
    _scSettingType.layer.borderWidth = 1;
    //_scSettingType.layer.backgroundColor = [UIColor lightGrayColor].CGColor;
    
    [_scSettingType addTarget: self action:@selector(onChgSettingType:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_scSettingType];
  }
  else {
    _scSettingType = nil;
    
    xPos = bWider?60:40;
    _lblBfs200Setting = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos, W - xPos*2, 25)];
    _lblBfs200Setting.textColor = [UIColor orangeColor];
    _lblBfs200Setting.font = [UIFont systemFontOfSize:16.0];
    _lblBfs200Setting.backgroundColor = [UIColor clearColor];
    _lblBfs200Setting.textAlignment = NSTextAlignmentCenter; //bIpad? NSTextAlignmentCenter: NSTextAlignmentRight;
    _lblBfs200Setting.text = @"BFS200 Router Setting";
    [self.view addSubview:_lblBfs200Setting];
  }
  
  yyPos += (bIpad? 60: 50);
  _lblRouterName = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos, W - xPos*2, 25)];
  _lblRouterName.textColor = [UIColor whiteColor];
  _lblRouterName.font = [UIFont
                         systemFontOfSize:16.0];
  _lblRouterName.backgroundColor = [UIColor clearColor];
  _lblRouterName.textAlignment = NSTextAlignmentLeft; //bIpad? NSTextAlignmentCenter: NSTextAlignmentRight;
  _lblRouterName.text = @"Connected Router";
  [self.view addSubview:_lblRouterName];
  
  UIImage* iBtn = [UIImage imageNamed:@"ic-refresh.png"];
  _btnRefreshRouter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnRefreshRouter.frame = CGRectMake(W - xPos + 2, yyPos, 28, 28); //W-40
  [_btnRefreshRouter setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnRefreshRouter addTarget:self action:@selector(onTapRefresh:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnRefreshRouter];
  
  xPos = (W - 200) / 2;
  yyPos += (bIpad? 50: 40);
  _txtPswdRouter =  [[UITextField alloc] initWithFrame:CGRectMake(xPos, yyPos, 200, 30)];
  _txtPswdRouter.textColor = [UIColor blackColor];
  _txtPswdRouter.backgroundColor = [UIColor whiteColor];
  _txtPswdRouter.font = [UIFont systemFontOfSize:bIpad?17:14];
  _txtPswdRouter.borderStyle = UITextBorderStyleRoundedRect;
  _txtPswdRouter.layer.cornerRadius = 12;
  _txtPswdRouter.keyboardType = UIKeyboardTypeDefault;//UIKeyboardTypeNumberPad;
  _txtPswdRouter.placeholder = @"Router Password"; //NSLocalizedString(@"Name", nil);
  [self.view addSubview: _txtPswdRouter];
  
  
  xPos = W/(bIpad?4:8);
  yyPos += (bIpad? 80: 70);
  _btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnCancel.frame = CGRectMake(xPos, yyPos, 100, 28);
  _btnCancel.backgroundColor = [UIColor lightGrayColor];
  [_btnCancel setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
  [_btnCancel setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
  _btnCancel.layer.masksToBounds = YES;
  _btnCancel.layer.cornerRadius = 4;
  [_btnCancel addTarget:self action:@selector(onSettingCancel:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnCancel];
  
  xPos = W - xPos - 100;
  _btnNext = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnNext.frame = CGRectMake(xPos, yyPos, 100, 28);
  _btnNext.backgroundColor = [UIColor whiteColor];
  _btnNext.layer.cornerRadius = 5;
  [_btnNext setTitle:@"Next" forState:UIControlStateNormal];
  //[_btnNext setTitle:NSLocalizedString(@"Next", nil) forState:UIControlStateNormal];
  //[_btnNext setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnNext addTarget:self action:@selector(onSettingCancel:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnNext];
  
  _btnSetting = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnSetting.frame = CGRectMake(xPos, yyPos, 100, 28);
  _btnSetting.backgroundColor = [UIColor lightGrayColor];
  [_btnSetting setTitle:@"Setting" forState:UIControlStateNormal];
  [_btnSetting setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  _btnSetting.layer.masksToBounds = YES;
  _btnSetting.layer.cornerRadius = 4;
  [_btnSetting addTarget:self action:@selector(onSettingCancel:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnSetting];
  _btnSetting.hidden = YES;
//
  
  xPos = (W - 64) / 2;
  yyPos += (bIpad? 80: 70);
  iBtn = [UIImage imageNamed:@"ic_router.png"];
  _ivRouter = [[UIImageView alloc] initWithImage:iBtn];
  _ivRouter.frame = CGRectMake(xPos, yyPos, 64, 90);
  [self.view addSubview:_ivRouter];
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) setConnectedRouter
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sConnSsid = [pApp connedWifiSSID];
  NSString* sInfo = [NSString stringWithFormat:@"Connected: %@", sConnSsid];
  _lblRouterName.text = sInfo;
  
  NSString* sMsg = @"";
  if(![sConnSsid hasPrefix:@"BFS200"]) {
    sMsg = @"Please connect to your router at first\n Then input your router's password";
  }
  _lblMsg.text = [NSString stringWithFormat:@"%@\n%@", sMsg, @"And tap Next"];
  _btnNext.enabled = [sInfo rangeOfString:@"No WiFi"].location == NSNotFound;
}

-(void) onTapRefresh:(id)sender
{
  _lblMsg.text = @"Refresh connected router...";
  
  [self setConnectedRouter];
  AudioServicesPlaySystemSound(1109);
  
}

- (void) mainAction:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

- (void) onChgSettingType:(id)sender
{
  NSInteger nSelTypeIdx = _scSettingType.selectedSegmentIndex;
  _lblMsg.text = (nSelTypeIdx==0)?@"BFS221 Router setting": @"BFS200 Router Setting";
}

-(Boolean)setWiFipassword : (NSString *)APname : (NSString *)password
{
  Boolean ret = false;
  Boolean isNewAP = true;
  //check previous data
  NSString *preWiFiAllData = @"";
  NSString *storeWiFiData = @"";
  NSString *storeWiFiAllData = @"";
  
  preWiFiAllData = [APInfo_DataFile objectForKey:@"APINFO"];
  
  NSArray *APData = [preWiFiAllData componentsSeparatedByString:@";"];
  NSArray *APItemInfo = nil;
  int APNum = (int)[APData count]-1;
  for (int i = 0; i < APNum; i++)
  {
    NSLog(@"<APP> set AP-%d:%@\n", i+1, [APData objectAtIndex:i]);
    
    APItemInfo = [ [APData objectAtIndex:i] componentsSeparatedByString:@","];
    if( [APname isEqualToString: [APItemInfo objectAtIndex:0] ] )
    {
      isNewAP = false;
      break;
    }
    
  }
  
  if (isNewAP) {//new
    
    if(preWiFiAllData==nil)
      preWiFiAllData = @"";
    
    storeWiFiAllData = [preWiFiAllData stringByAppendingString:APname];
    storeWiFiAllData = [storeWiFiAllData stringByAppendingString:@","];
    storeWiFiAllData = [storeWiFiAllData stringByAppendingString:password];
    storeWiFiAllData = [storeWiFiAllData stringByAppendingString:@";"];
  }
  else{//update
    for (int i = 0; i < APNum; i++)
    {
      
      APItemInfo = [ [APData objectAtIndex:i] componentsSeparatedByString:@","];
      if( [APname isEqualToString: [APItemInfo objectAtIndex:0] ] )
      {
        storeWiFiData = [NSString stringWithFormat:@"%@,%@;", [APItemInfo objectAtIndex:0], password];
      }else{
        storeWiFiData = [NSString stringWithFormat:@"%@,%@;", [APItemInfo objectAtIndex:0], [APItemInfo objectAtIndex:1]];
      }
      storeWiFiAllData = [storeWiFiAllData stringByAppendingString:storeWiFiData];
    }
  }
  
  
  [APInfo_DataFile setValue:storeWiFiAllData forKey:@"APINFO"];
  [APInfo_DataFile synchronize];
  
  ret = true;
  //[self.mySimpleConfig rtk_sc_set_ssid: APname];
  //[self.mySimpleConfig rtk_sc_set_password: password];
  SSID = APname;
  AP_password = password;
  return ret;
}

- (void) sendRouterPassword
{
  NSString* sRouter = _lblRouterName.text;
  NSRange rng = [sRouter rangeOfString:@": "];
  if(rng.location != NSNotFound) {
    sRouter = [sRouter substringFromIndex:rng.location+2];
  }
  NSString* sPswd = _txtPswdRouter.text;
  _lblMsg.text = [NSString stringWithFormat:@"Try to Connect %@ with pswd %@", sRouter, sPswd];
  
  [self setWiFipassword : sRouter : sPswd];
  
  [NSThread sleepForTimeInterval:0.75];
  [self startCongigRouter];
  
}

- (void) onSettingCancel:(id)sender
{
  if(sender == _btnNext) {
    _lblMsg.text = @"Next";
    _btnNext.hidden = YES;
    _btnSetting.hidden = NO;
    //[self wifiSacleConn:_ScaleHostPort IpAddr:_ScaleHostIpAddr];
    [self sendRouterPassword];
  }
  else {
    if(_txtPswdRouter.isFirstResponder)
      [_txtPswdRouter resignFirstResponder];
    _lblMsg.text = (sender==_btnSetting)?@"setting": NSLocalizedString(@"Cancel", nil);
  }
}

- (void) keyboardWillShow:(id)sender
{
  _lblMsg.text = @"Please input your router password";
}


- (BOOL) isNcitDeviceWithSsid:(NSString*) sConnSsid
{
  //BOOL bOK = [sConnSsid hasPrefix:@"DBS2"] || [sConnSsid hasPrefix:@"DB2"] || [sConnSsid hasPrefix:@"RIS2"] || [sConnSsid hasPrefix:@"IS2"];
  //return bOK;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  BOOL bIsNcitDev = [pApp isNcitDeviceWithSsid:sConnSsid];
  return bIsNcitDev;
}

#pragma mark -  wifi reach





- (void) recvedWiFiHexData:(UInt8*)pData len:(int)nLen
{
  
}

@end*/
